package com.owlsmart.bluecat.fragment;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.ErrorView;
import com.dueeeke.videocontroller.component.GestureView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.google.gson.Gson;
import com.owlsmart.bluecat.R;
import com.owlsmart.bluecat.adapter.VideoAdapter;
import com.owlsmart.bluecat.api.Api;
import com.owlsmart.bluecat.api.ApiConfig;
import com.owlsmart.bluecat.api.TitleCallback;
import com.owlsmart.bluecat.entity.VideoEntity;
import com.owlsmart.bluecat.entity.VideoListResponse;
import com.owlsmart.bluecat.listener.OnItemChildClickListener;
import com.owlsmart.bluecat.utils.Tag;
import com.owlsmart.bluecat.utils.Utils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

// 播放器要实现 OnItemChildClickListener
public class VideoFragment extends BaseFragment implements OnItemChildClickListener {
    private final String TAG = "VideoFragment";

    private String title;
    private int categoryId;

    // 刷新使用的属性
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;

    private int pageNum = 1;
    private VideoAdapter videoAdapter;
    private List<VideoEntity> datas = new ArrayList<>();

    // 全局布局管理器，兼容播放器的
    private LinearLayoutManager linearLayoutManager;

    // 视频播放器需要用的
    protected VideoView mVideoView;
    protected StandardVideoController mController;
    protected ErrorView mErrorView;
    protected CompleteView mCompleteView;
    protected TitleView mTitleView;
    /**
     * 当前播放的位置 记录播放
     */
    protected int mCurPos = -1;
    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    protected int mLastPos = mCurPos;

    // 在UI线程里面执行
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    videoAdapter.setDatas(datas);
                    // 通知recycleView刷新页面
                    videoAdapter.notifyDataSetChanged();
            }
        }
    };


    public VideoFragment() {
    }

    public static VideoFragment newInstance(int categoryId) {
        VideoFragment fragment = new VideoFragment();
        fragment.categoryId = categoryId;
        return fragment;
    }

    public static VideoFragment newInstanceTitle(String title) {
        VideoFragment fragment = new VideoFragment();
        fragment.title = title;
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initView() {
        // 初始化播放器
        initVideoView();
        //改造后刷新
        recyclerView = mRootView.findViewById(R.id.recycleView);
        refreshLayout = mRootView.findViewById(R.id.refreshLayout);

    }

    @Override
    protected void initDate() {
        //getActivity()获取父控件（fragment获取父activity控件对象）
        linearLayoutManager = new LinearLayoutManager(getActivity());
        //设置垂直排列
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        videoAdapter = new VideoAdapter(getActivity());
        // 设置点击事件，绑定之后设置
        videoAdapter.setOnItemChildClickListener(this);

        //渲染到recycle view
        recyclerView.setAdapter(videoAdapter);
        // 添加监听事件
        recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                FrameLayout playerContainer = view.findViewById(R.id.player_container);
                View v = playerContainer.getChildAt(0);
                if (v != null && v == mVideoView && !mVideoView.isFullScreen()) {
                    releaseVideoView();
                }
            }
        });

        // 设置刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                // 每次刷新，首页
                pageNum = 1;
                // 调用刷新的方法并且设置为true
                getVideoList(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                // 加载，不需要刷新
                // refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                // 每次加载 pageNum++
                pageNum++;
                getVideoList(false);
                Log.d(TAG, "第页码数字" + pageNum);

            }
        });

        // 首次刷新为true
        getVideoList(true);
    }

    protected void initVideoView() {
        mVideoView = new VideoView(getActivity());
        mVideoView.setOnStateChangeListener(new com.dueeeke.videoplayer.player.VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == com.dueeeke.videoplayer.player.VideoView.STATE_IDLE) {
                    Utils.removeViewFormParent(mVideoView);
                    mLastPos = mCurPos;
                    mCurPos = -1;
                }
            }
        });
        mController = new StandardVideoController(getActivity());
        mErrorView = new ErrorView(getActivity());
        mController.addControlComponent(mErrorView);
        mCompleteView = new CompleteView(getActivity());
        mController.addControlComponent(mCompleteView);
        mTitleView = new TitleView(getActivity());
        mController.addControlComponent(mTitleView);
        //
        mController.addControlComponent(new VodControlView(getActivity()));
        mController.addControlComponent(new GestureView(getActivity()));
        mController.setEnableOrientation(true);
        mVideoView.setVideoController(mController);
    }

    // 以下都是和视频播放相关 直到releaseVideoView释放视频
    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected void pause() {
        releaseVideoView();
    }

    @Override
    public void onResume() {
        super.onResume();
        resume();
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected void resume() {
        if (mLastPos == -1)
            return;
        //恢复上次播放的位置
        startPlay(mLastPos);
    }

    /**
     * PrepareView被点击
     * 触发startPlay进行播放(记录下标)
     * 通过下标可以得到当前的后端返回的实体类，包含URL
     */
    @Override
    public void onItemChildClick(int position) {
        startPlay(position);
    }

    /**
     * 开始播放
     *
     * @param position 列表位置
     */
    protected void startPlay(int position) {
        if (mCurPos == position) return;
        if (mCurPos != -1) {
            releaseVideoView();
        }
        // datas自定义的datas，和VideoEntity
        VideoEntity videoEntity = datas.get(position);
        //边播边存
//        String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl());
//        mVideoView.setUrl(proxyUrl);

        // 设置后端返回的URL
        mVideoView.setUrl(videoEntity.getPlayurl());
        mTitleView.setTitle(videoEntity.getVtitle());
        View itemView = linearLayoutManager.findViewByPosition(position);
        if (itemView == null) return;
        // 自己写的VideoAdapter
        VideoAdapter.ViewHolder viewHolder = (VideoAdapter.ViewHolder) itemView.getTag();
        //把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController.addControlComponent(viewHolder.mPrepareView, true);
        Utils.removeViewFormParent(mVideoView);
        viewHolder.mPlayerContainer.addView(mVideoView, 0);
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        getVideoViewManager().add(mVideoView, Tag.LIST);
        mVideoView.start();
        mCurPos = position;

    }

    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if (getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mCurPos = -1;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * // 周期函数，在父类中控制，这里可以不用
     *
     * @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
     * Bundle savedInstanceState) {
     * View v = inflater.inflate(R.layout.fragment_video, container, false);
     * <p>
     * return v;
     * }
     * <p>
     * // 另外一个生命周期函数，在父类中控制，这里可以不用
     * @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
     * super.onViewCreated(view, savedInstanceState);
     * <p>
     * // //准备数据
     * // List<VideoEntity> datas = new ArrayList<>();
     * // for (int i = 0; i < 8; i++) {
     * //     VideoEntity videoEntity = new VideoEntity();
     * //     videoEntity.setTitle("韭菜盒子的标题");
     * //     videoEntity.setName("大胃王");
     * //     videoEntity.setDzCount(i * 2);
     * //     videoEntity.setCollectionCount(i * 4);
     * //     videoEntity.setCommentCOunt(i * 6);
     * //     datas.add(videoEntity);
     * // }
     * <p>
     * }
     */

    // 获取视频列表
    private void getVideoList(final boolean isRefresh) {
        // String token = getStringFromSp("token");
        // if (!StringUtils.isEmpty(token)) {
        HashMap<String, Object> params = new HashMap<>();
        // params.put("token", token);
        params.put("page", pageNum);
        params.put("limit", ApiConfig.PAGE_SIZE);
        // params.put("categoryId", categoryId);
        Api.config(ApiConfig.VIDEO_LIST, params).getRequest(getActivity(), new TitleCallback() {
            @Override
            public void onSuccess(String res) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }

                final VideoListResponse response = new Gson().fromJson(res, VideoListResponse.class);
                if (response != null && response.getCode() == 0) {

                    List<VideoEntity> list = response.getPage().getList();
                    if (list != null && list.size() > 0) {
                        if (isRefresh) {
                            datas = list;
                        } else {
                            datas.addAll(list);
                        }
                        mHandler.sendEmptyMessage(0);

                    } else {
                        if (isRefresh) {
                            // 换成异步toast就可以不操作UI了
                            // showToast("加载无数据");
                            showToastSync("加载无数据");
                        } else {
                            showToastSync("没有更多数据了");
                        }
                    }


                }
            }

            @Override
            public void onFailure(Exception e) {
                // 接口请求失败，关闭动画
                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }
            }
        });
        // } else {
        //     navigateTo(LoginActivity.class);
        // }

    }

    // 视频管理器
    protected VideoViewManager getVideoViewManager() {
        return VideoViewManager.instance();
    }
}